<?php

namespace Biz\model;

/**
 *
 * @author lee
 *
 */

use Biz\cache\Shop as cShop;
use Biz\module\Classes\ShopStatus as clsShopStatus;
use Biz\validate\ShopBasicInfo as vShopBasicInfo;
use Doraemon\tools\HhzClient;
use Doraemon\tools\HhzEnv;
use Medoo\Medoo;


class ShopBasicInfo extends \Doraemon\pockets\datebase\BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'shop_basic_info(sbi)';

    const _SUB_TABLE = false;


    //店铺类型
    const TYPE_COMPANY = 1;//公司账户
    const TYPE_PERSONAL = 2;//个人账户

    //运营方类型
    const OPERATOR_TYPE_SELF = 2;//自营店铺

    //商家状态
    const STATUS_NORMAL = 0;//待提交资料
    const STATUS_WAIT_AUDIT = 1;//待审核
    const STATUS_REJECT = 2;//已驳回
    const STATUS_WAIT_PAY_DEPOSIT = 4;//待交保证金
    const STATUS_OPENED = 5;//已开店
    const STATUS_CLOSED = 6;//已关店
    const STATUS_FROZEN = 7;//已冻结

    //冻结原因
    const FROZEN_REASON_CLOSE = 1;//申请关店
    const FROZEN_REASON_GENERAL = 2;//一般违规
    const FROZEN_REASON_SERIOUS = 3;//严重违规


    public static $typeDesc = [
        self::TYPE_COMPANY => '公司账户',
        self::TYPE_PERSONAL => '个人账户',
    ];

    public static $typeTag = [
        self::TYPE_COMPANY => 'company',
        self::TYPE_PERSONAL => 'personal',
    ];

    public static $statusDesc = [
        self::STATUS_NORMAL => '待提交资料',
        self::STATUS_WAIT_AUDIT => '待审核',
        self::STATUS_REJECT => '已驳回',
        self::STATUS_WAIT_PAY_DEPOSIT => '待交保证金',
        self::STATUS_OPENED => '已开店',
        self::STATUS_CLOSED => '已关店',
        self::STATUS_FROZEN => '已冻结'
    ];

    public static $frozenReason = [
        self::FROZEN_REASON_CLOSE => '申请关店',
        self::FROZEN_REASON_GENERAL => '【一般违规】扣分累计达到48分',
        self::FROZEN_REASON_SERIOUS => '【严重违规】扣分累计达到36分'
    ];


    //允许通过createOrEdit操作的字段列表，进行输入转换
    protected static $fields = [
        'uid',
        'shop_id',
        'type',
        'name' => ['trim', 'strip_tags'],
        'intro' => ['trim', 'strip_tags'],
        'status',
    ];

    //判断商家是否已完成注册且成功
    //false 未完成注册
    //true 已完成注册流程
    public static function checkShopSignupStatus($uid)
    {
        if (!self::checkExists($uid)) {
            return false;
        }

        $has = self::has(['uid' => $uid, 'status[!]' => [self::STATUS_NORMAL, self::STATUS_REJECT]]);

        if ($has) {
            return true;
        }

        return false;
    }

    //判断账户是否存在
    public static function checkExists($uid)
    {
        $has = self::has(['uid' => $uid]);

        return $has;
    }

    //查询基本信息
    public static function getInfo($uid, $from = '')
    {
        $info = self::get("*", ['uid' => $uid]);

        self::formatInfo($info, $from);

        return $info;
    }

    public static function getInfoByName($shopName, $from = '')
    {
        $info = self::get("*", ['name' => $shopName]);

        self::formatInfo($info, $from);

        return $info;
    }

    public static function getInfoList($uids, $from = '')
    {
        $list = self::select("*", ['uid' => $uids, 'ORDER' => ['addtime' => 'DESC']]);
        $formatData = [];
        $list = empty($list) ? [] : $list;
        foreach ($list as $info) {
            self::formatInfo($info, $from);

            $formatData[$info["uid"]] = $info;
        }
        return $formatData;
    }

    public static function getShopInfoList($shopIds, $field = '*')
    {
        $list = [];
        if($shopIds && is_array($shopIds)) {
            $list = self::select($field, ['shop_id' => $shopIds]);

            $list = array_column($list, null, 'shop_id');
        }

        return $list;
    }


    public static function formatInfo(&$info, $from = '')
    {
        if (empty($info)) {
            return;
        }


        foreach ($info as $key => &$value) {
            switch ($key) {
                case 'type':
                    $info['type_desc'] = self::$typeDesc[$value];
                    if ($info['type'] == self::TYPE_COMPANY) {
                        $info['type_tag'] = self::$typeTag[self::TYPE_COMPANY];
                    } elseif ($info['type'] == self::TYPE_PERSONAL) {
                        $info['type_tag'] = self::$typeTag[self::TYPE_PERSONAL];
                    }
                    break;
                case 'name':
                    $info['shop_name'] = $info['name'];
                    break;
                case 'status':
                    $info['status_desc'] = self::$statusDesc[$value];
                    break;
            }
        }

        if ($from == 'adm') {
            $info['actions'] = clsShopStatus::getAdminActionList($info['status']);
        } else {
            if ($from == 'app') {
//            $info['imgurl'] = ShopIdentifyImage::getImgList($info['uid'], $info['type'], ['other']) ? 'http://img.hhz1.cn/Op-imageShow/ef49e303l01000000p5vykk?w=129&h=36&iv=1' : '';
                $info['imgurl'] = '';
                $info['score'] = ShopComments::getAvgScore($info['shop_id']);
            }
        }
    }

    //保存商家信息
    public static function createOrEdit($uid, $data, $scenes = null, $method = null)
    {
        try {

            if (is_null($method)) {
                $has = self::has_master(Medoo::raw(' where uid=:uid for update', [':uid' => $uid]));


                $method = $has ? 'update' : 'insert';

            }

            if (!is_null($scenes)) {
                //提交字段进行校验
                if (!vShopBasicInfo::validate($data, $scenes)) {

                    $msg = vShopBasicInfo::firstError();

                    throw new \Exception($msg);
                }

            }

            $data = self::buidData($data);

            switch ($method) {
                case 'insert':
                    $data['shop_id'] = $uid;
                    $data['uid'] = $uid;
                    $data['addtime'] = date('Y-m-d H:i:s');

                    $ret = self::insert($data);
                    break;
                case 'update':
                    $ret = self::update($data, ['uid' => $uid]);
                    cShop::mDelItems($uid);
                    break;
            }


            if ($ret->errorCode() !== '00000') {
                throw new \Exception('数据库操作错误');
            }
        } catch (\Exception $e) {


            throw $e;
        }
    }

    public static function getShopId($uid)
    {
        return self::get('shop_id', ['uid' => $uid]);
    }

    public static function selectFieldsByFilter($fields = [], $where = [])
    {

        $results = self::select($fields, $where);
        if (count($fields) == 1) {

            return array_map(function ($result) use ($fields) {
                return $result[$fields[0]];
            }, $results);
        } else {
            return $results;
        }


    }

    public static function selectCountByFilter($where = [])
    {
        return self::count('*', $where);
    }

    public static function updateByField($field, $where)
    {
        $result = self::update($field, $where)->rowCount();
        if ($result && (isset($where['uid']) || isset($where['shop_id']))) {
            cShop::mDelItems(isset($where['uid']) ? $where['uid'] : $where['shop_id']);
        }
        return $result;
    }

    public static function getShopInfo($shopId, $field = '*')
    {
        if($shopId && is_array($shopId)) {
            return self::get($field, ['shop_id' => $shopId]);
        }
        return [];

    }

    public static function checkShopIsForzen($shopId)
    {
        $has = self::has(['shop_id' => $shopId, 'status' => self::STATUS_FROZEN]);
        return $has;
    }

    public static function getByWhere($method, $fields, $where = '')
    {
        return self::$method($fields, $where);
    }

    public static function checkIsSelfOperated($shopId){
        return true;
        if($shopId == 4372030 || HhzEnv::isShopTest() || HhzEnv::isShopHaoHaoCe()){
            return true;
        }
/*
        $info = self::get(['operator_type'],['shop_id'=>$shopId]);
        if(!empty($info)){
            if($info['operator_type'] == self::OPERATOR_TYPE_SELF){
                return true;
            }*/
        return false;
    }

}

